//
//  LQYSelectCityViewController.m
//  FAKER
//
//  Created by dllo on 15/11/9.
//  Copyright © 2015年 YHLai. All rights reserved.
//

#import "LQYSelectCityViewController.h"
#import "AllHeader.h"
#import "FitHeader.h"
#import "pinyin.h"
@interface LQYSelectCityViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)BaseClassTableView *tableView;

@property(nonatomic, retain)NSMutableArray *hotCitiesArray;
@property(nonatomic, retain)NSMutableArray *normalCitiesNameArray;
@property(nonatomic, retain)NSMutableArray *sectionArray;
@property(nonatomic, retain)NSMutableArray *cityArray;
@property(nonatomic, retain)NSMutableDictionary *CitiesDic;

@property(nonatomic, retain)UIView *contentView;

@end

@implementation LQYSelectCityViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self changeColor];
}
- (void)changeColor
{
    if (NSUSERDEFAULTS_NIGHT) {
        _tableView.backgroundColor = [UIColor blackColor];
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.sectionIndexColor = [UIColor lightGrayColor];
    }
    else{
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.sectionIndexColor = [UIColor blackColor];
    }
    [_tableView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"選擇你所在的城市";
    ADD_NSNOTIFICATIONCENTER_OBSERVER;
    
    
}
-(void)loadView
{
    [super loadView];
    [self getData];
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    _searchBar.placeholder = @"我在...";
    _searchBar.delegate = self;
    _searchBar.tintColor = [UIColor whiteColor];
    
    
    [self.view addSubview:_searchBar];
    
    

    _tableView = [[BaseClassTableView alloc]initWithFrame:CGRectMake(0, _searchBar.Y + _searchBar.HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49 - 40 * FITHEIGHT) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.sectionIndexMinimumDisplayRowCount = 200;
    [self.view addSubview:_tableView];
    
    _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49)];
    _contentView.backgroundColor = [UIColor blackColor];
    _contentView.alpha = 0;
    UITapGestureRecognizer *releaseKeyBoard = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(searchBarCancelButtonClicked:)];
    [_contentView addGestureRecognizer:releaseKeyBoard];
    [self.view addSubview:_contentView];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sectionArray.count;
}
#pragma mark    導航條 
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return _sectionArray;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"热门城市";
    }
    else{
        return _sectionArray[section];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return [[_CitiesDic objectForKey:@"热门城市"] count];
    }
    else{
        return [[_CitiesDic objectForKey:_sectionArray[section]] count];
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSString *keyWord = [self.dataSourceArray[indexPath.row]valueForKey:@"title"];
//    NSRange range = [keyWord rangeOfString:self.searchBar.text];
//    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc]initWithString:keyWord];
//    [attrString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName,[UIFont systemFontOfSize:30], NSFontAttributeName, nil] range:range];
    
    
    static NSString *identifie = @"cell";
    BaseClassTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifie];
    if (!cell)
    {
        cell = [[BaseClassTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifie];
    }
    
    if (indexPath.section == 0) {
        cell.textLabel.text = [[_CitiesDic objectForKey:@"热门城市"]objectAtIndex:indexPath.row];
    }
    else{
        cell.textLabel.text = [[_CitiesDic objectForKey:_sectionArray[indexPath.section]]objectAtIndex:indexPath.row];
    }
    if (NSUSERDEFAULTS_NIGHT) {
        cell.textLabel.textColor = [UIColor lightGrayColor];
    }
    else{
        cell.textLabel.textColor = [UIColor blackColor];
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"%@", [[_CitiesDic objectForKey:_sectionArray[indexPath.section]]objectAtIndex:indexPath.row]);
    if (indexPath.section == 0) {
        self.block([[_CitiesDic objectForKey:@"热门城市"]objectAtIndex:indexPath.row]);
    }
    else{
        self.block([[_CitiesDic objectForKey:_sectionArray[indexPath.section]]objectAtIndex:indexPath.row]);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)getData
{
    self.sectionArray = [NSMutableArray array];
    self.hotCitiesArray = [NSMutableArray array];
    self.normalCitiesNameArray = [NSMutableArray array];
    self.cityArray = [NSMutableArray array];
    self.CitiesDic = [NSMutableDictionary dictionary];
    NSString *path = [[NSBundle mainBundle]pathForResource:@"city_list" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *subDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *dataDic = [subDic valueForKey:@"data"];
    NSArray *hotCitiesArray = [dataDic objectForKey:@"hot_cities"];
    for (NSDictionary *dic in hotCitiesArray)
    {
        LQYCityModal *modal = [[LQYCityModal alloc]init];
        [modal setValuesForKeysWithDictionary:dic];
        [_hotCitiesArray addObject:modal.name];
    }
    _CitiesDic = [NSMutableDictionary dictionary];
    [_CitiesDic setValue:_hotCitiesArray forKey:@"热门城市"];
    
    NSArray *normalCitiesArray = [dataDic objectForKey:@"cities"];
    for (NSDictionary *dic in normalCitiesArray)
    {
        LQYCityModal *modal = [[LQYCityModal alloc]init];
        modal.name = [dic objectForKey:@"name"];
        NSString *cityLetter = [NSString stringWithFormat:@"%c", pinyinFirstLetter([modal.name characterAtIndex:0])];
        
        LQYCitiesModal *city = [[LQYCitiesModal alloc]init];
        city.citiesLetter = cityLetter;
        city.citiesName = modal.name;
        [_normalCitiesNameArray addObject:city];
    }
    
    //遍歷數組
    for (LQYCitiesModal *city in _normalCitiesNameArray)
    {
        //字典里有此key
        if ([_CitiesDic valueForKey:city.citiesLetter]) {
            //找到字典中該key對應的數組并添加
            [[_CitiesDic objectForKey:city.citiesLetter] addObject:city.citiesName];
        }
        //字典里沒有此key
        else{
            //數組初始化
            _cityArray = [NSMutableArray array];
            //創建key對應的數組
            [_CitiesDic setObject:_cityArray forKey:city.citiesLetter];
            //將城市名元素加入數組
            [_cityArray addObject:city.citiesName];
        }
    }
    [_sectionArray addObjectsFromArray:[_CitiesDic allKeys]];
    [_sectionArray sortUsingSelector:@selector(compare:)];
    [_sectionArray removeLastObject];
    [_sectionArray insertObject:@"热" atIndex:0];
}


#pragma mark 點擊鍵盤search鍵執行的方法
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [UIView animateWithDuration:0.5 animations:^{
        _contentView.alpha = 0;
    }];
    [_searchBar setShowsCancelButton:NO animated:YES];
    [_searchBar resignFirstResponder];
}
#pragma mark 點擊searchBar執行的方法
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [_searchBar setShowsCancelButton:YES animated:YES];
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            cancel.layer.borderWidth = 2;
            cancel.layer.borderColor = (__bridge CGColorRef _Nullable)([UIColor lightGrayColor]);
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    _contentView.hidden = NO;
    [UIView animateWithDuration:0.5 animations:^{
        _contentView.alpha = 0.7;
    }];
    return YES;
}
#pragma mark 点击取消按钮执行的方法
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
    [_searchBar setShowsCancelButton:NO animated:YES];
    [UIView animateWithDuration:0.5 animations:^{
        _contentView.alpha = 0;
    }];
    _searchBar.text = nil;
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    
}
#pragma mark searchBar文字内容变换时执行的方法
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"15351");
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
